<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sj" uri="/struts-jquery-tags" %> 
<%@ taglib prefix="display" uri="http://displaytag.sf.net" %>
<script type='text/javascript'>
$(document).ready(function() {

	// jquery Tabs
	$("#tabView").tabs({
	    select: function(event, ui) {
	        var url = $.data(ui.tab, 'load.tabs');
	        if ( url ) {
	            location.href = url;
	            return false;
	        }
	        return true;
	    },
	    selected: 0
	});

	// json for language type list
	var languageData = [
		<s:iterator value="languages" var="language" status="languageStatus" > {
                "id": "<s:property value="id" />",
                "name": "<s:property value="name" />"
	} <s:if test="!#languageStatus.last">,</s:if>
	</s:iterator>
	];

	// jquery populate LanguageTypeId Select List
	$(document).ready(function() {
    	var select = $("#formRowLanguageId").get(0);
        select.options.length = 0;
        $(languageData).each(function(index, item) {
        	select.options[select.options.length] =
        	new Option(item.name, item.id); 
        });
                                                                                                                
    });

    // json for questionTypeList
	var questionData = [
	    <s:iterator value="questionTypes" var="question" status="questionTypeStatus" > {
	    	"id": "<s:property value="id" />",
	        "name": "<s:property value="name" />"
	    } <s:if test="!#questionTypeStatus.last">,</s:if>
	    </s:iterator>
	];

    // jquery populate Question Type Id List
	$(document).ready(function() {
		var select = $("#formRowQuestionType").get(0);
	    select.options.length = 0;
	    $(questionData).each(function(index, item) {
	    	select.options[select.options.length] =
	    	new Option(item.name, item.id); 
	    });
	                                                                                                                            
	});
	
	var questionNum = $( "#questionNum" ),
		languageId = $( "#languageId" ),
		questionText = $( "#questionText" ),
		weight = $( "#weight" ),
		questionTypeId = $( "#questionTypeId" ),
		allFields = $( [] ).add( questionNum ).add( languageId ).add( questionText ).add( weight).add( questionTypeId),
		tips = $( ".validateTips" );

	function updateTips( t ) {
		tips
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 500 );
	}

	function checkLength( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTips( "Length of " + n + " must be between " +
				min + " and " + max + "." );
			return false;
		} else {
			return true;
		}
	}

	function checkRange( o, n, min, max ) {
		if ( o.val() < min || o.val() > max ) {
			o.addClass( "ui-state-error" );
			updateTips( n + " must be between " +
				min + " and " + max + "." );
			return false;
		} else {
			return true;
		}
	}
	
	function checkRegexp( o, regexp, n ) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" );
			updateTips( n );
			return false;
		} else {
			return true;
		}
	}

	function validateForm() {
	 alert("Validating DELETE");
	 return true;
	}
	
	// Populate question update Dialog Box
	$(document).ready(function () {
	       $(".row-dialog").live("click", function() {
	              /*
	              * Populate data here for any row prior to calling open.
	              */
	              $("#formRowId").val($(this).find(".row-id").text());
	              $("#formRowWeight").val($(this).find(".row-weight").text());
	              $("#formRowLanguageId").val($(this).find(".row-languageId").text());
	              $("#formRowQuestionType").val($(this).find(".row-questionType").text());
	              $("#formRowQuestionText").val($(this).find(".row-questionText").text());
	              
	              $("#questionDialog").dialog("open");
	       });
	});

	// Update/Delete Dialog Box
	$( "#questionDialog" ).dialog({
		autoOpen: false,
		height: 250,
		width: 320,
		modal: true,
		buttons: {
			"Update": function() {
			   alert("Need to add code to UPDATE the DATABASE");
			   $( this ).dialog( "close" );
			},
			"Delete": function () {
		       $( this ).dialog( "close" );
		       $("#dialog-deleteQuestion").dialog("open");
			},
			Cancel: function() {
			   $( this ).dialog( "close" );
			}
    	}
	});
	
	// Code to Confirm you want to DELETE a Question Dialog Box
	$( "#dialog-deleteQuestion" ).dialog({
		autoOpen: false,
		height: 150,
		width: 300,
		modal: true,
	    buttons: {
			"YES": function() {
				// Need to Add code to DELETE the Question
			    alert("Need to add code to DELETE THIS QUESTION");
	 			$( this ).dialog( "close" );
			},
			
			"NO": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});

	// Add Question Dialog Box
	$( "#dialog-form" ).dialog({
		autoOpen: false,
		height: 320,
		width: 350,
		modal: true,
		buttons: {
			"ADD": function() {
				var bValid = true;
				allFields.removeClass( "ui-state-error" );

				bValid = bValid && checkRange( questionNum, "Question Number", 1, 50 );
  				bValid = bValid && checkRegexp( weight, /^([0-9][\.][0-9])/, "Please Enter a Decimal value. ex (1.0)" );
				bValid = bValid && checkLength( questionText, "Question Text", 5, 250 );

                var lang = languageId.val();
                if ( lang == "1" ) 
                    var newLang = "English";
                else if ( lang == "2" )
                    var newLang = "Spanish";

                var questionType = questionTypeId.val();
                if (questionType == "1") 
                    var newType = "Yes/No";
                else if ( questionType == "2" )
                    var newType = "Multiple Choice";
                else if ( questionType == "3" )
                    var newType = "Scale";
                
				if ( bValid ) {
					$( "#questions tbody" ).append( "<tr class='row-dialog'>" + 
						"<td class='row-id'>" + questionNum.val() + "</td>" + 
						"<td class='row-languageId'>" + newLang + "</td>" + 
						"<td class='row-weight'>" + weight.val() + "</td>" + 
						"<td class='row-questionType'>" + newType + "</td>" + 
						"<td class='row-questionText'>" + questionText.val() + "</td>" +
					"</tr>" ); 
						$( this ).dialog( "close" );
				}
			},
			
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});

	// Code to Confirm you want to Save Questions Dialog Box
	$( "#dialog-save" ).dialog({
		autoOpen: false,
		height: 150,
		width: 300,
		modal: true,
	    buttons: {
			"SAVE": function() {
				// Need to Add code to save to Database
			    alert("Need to add code to SAVE to the DATABASE");
	 			$( this ).dialog( "close" );
			},
			"NO": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});
	
	$( "#create-question" )
	.button()
	.click(function() {
		$( "#dialog-form" ).dialog( "open" );
	});

	$( "#save-questions" )
	.button()
	.click(function() {
		$( "#dialog-save" ).dialog( "open" );
	});
	
});
</script>

         <div id="tabView">
            <ul>
               <li><a href="#surveyDetail">Survey Detail</a></li>
               <s:set var="id" scope="page" value="id" /> 
               <li><a href="#questionDetail">Survey Questions</a></li> 
            </ul>
            <div id="surveyDetail">                  
                <s:actionerror />
                <s:form namespace="/survey" action="update" id="entity" onsubmit="return validateForm()">
                	<s:textfield name="name" label="%{getText('label.entity.name')}" size="20" maxlength="20" required="true" />
	                <s:textfield name="vxml" label="%{getText('label.entity.vxml')}" size="30" maxlength="255" required="false"/>
    	            <s:textfield name="numberOfQuestions" label="%{getText('label.entity.numberOfQuestions')}" size="4" maxlength="2" required="true" />
        	        <s:select name="category" label="%{getText('label.entity.category')}" list="categories" listKey="id" listValue="name"  />
            	    <s:select name="type" label="%{getText('label.entity.type')}" list="surveyTypes"  />
                	<s:radio name="voiceRecording" label="%{getText('label.entity.voiceRecording')}" list="#{'0':'No','1':'Yes'}" value='voiceRecording' />
	                <s:radio name="resultFollowup" label="%{getText('label.entity.resultFollowup')}" list="#{'false':'No','true':'Yes'}" value='resultFollowup' />
    	            <s:radio name="displayResultAverage" label="%{getText('label.entity.displayResultAverage')}" list="#{'false':'No','true':'Yes'}" value='displayResultAverage' />
        	        <s:radio name="status" label="%{getText('label.entity.status')}" list="#{'Inactive':'Inactive','Active':'Active'}" value='status' />
            	    <table>         
                	    <tr>
                    		<td colspan="2">
                        		<br />
 	    	                   	<input type="submit" value="Save" class="ui-button ui-state-default ui-corner-all" onclick="location.href='<s:url namespace="/survey" action="update" id="entity" includeParams="none"/>'; return true;" /> &nbsp;
 	    	                   	<input type="submit" value="Cancel" class="ui-button ui-state-default ui-corner-all" onclick="location.href='<s:url namespace="/survey" action="list" includeParams="none" />'; return false;" /> &nbsp;
    	                    	<input type="submit" value="Delete" class="ui-button ui-state-default ui-corner-all" onclick="location.href='<s:url namespace="/survey" action="delete" includeParams="none" />'; return false;"  /> 
            	         	</td>
                	  	</tr>
                	</table>           
                </s:form>
            </div>
            <div id="questionDetail">                  
                <s:url id="remoteurl" action="list" id="entity"/>     
                <sj:dialog id="mydialog3" href="%{remoteurl}" title="Survey Questions" autoOpen="false"/>   
           
                <div class="questionClass">
					<div id="dialog-form" title="Create New Question">
						<p class="validateTips">All form fields are required.</p>

						<form>
							<fieldset>
                            	<s:textfield name="questionNum" label="%{getText('label.entity.questionNum')}" size="2" maxlength="2" required="true" /><br>
  	                            <s:textfield name="weight" label="%{getText('label.entity.weight')}" value="1.0" size="3" maxlength="3" required="true" /><br>
				                <s:select name="languageId" label="%{getText('label.entity.languageId')}" list="languages" listKey="id" listValue="name"  /><br>
				                <s:select name="questionTypeId" label="%{getText('label.entity.questionTypeId')}" list="questionTypes" listKey="id" listValue="name"  />    <br>
								<s:textarea name="questionText" label="%{getText('label.entity.questionText')}" cols="40" rows="3" required="true" /> <br>
							</fieldset>
						</form>
					</div>
				
					<div id="dialog-save" title="Save Questions">
						<p> Are you sure you want to save the Questions?</p>
					</div>
			
					<div id="dialog-deleteQuestion" title="Delete Question">
						<p> Are you sure you want to Delete this Question?</p>
					</div>
				
					<div id="questions-contain" class="ui-widget">
						<table id="questions" class="ui-widget ui-widget-content">
							<thead>
             					<h4>Click Question to update</h4>
								<tr class="ui-widget-header ">
									<th>Num</th>
									<th>Language</th>
									<th>Weight</th>
									<th>Type</th>
									<th>Question Text</th>
								</tr>
							</thead>
							<tbody>
								<s:iterator var="question" value="questions">
									<tr class="row-dialog">
										<td class="row-id"><s:property value="questionId"/></td>
										<td class="row-languageId"><s:property value="languageId"/></td>
										<td class="row-weight"><s:property value="weight"/></td>	
										<td class="row-questionType"><s:property value="questionTypeId"/></td>	
										<td class="row-questionText"><s:property value="questionText"/></td>	
									</tr>
								</s:iterator>
								<sj:dialog id="questionDialog" title="Update Question" autoOpen="false" >
									<label for="rowId">Question Number</label> <input id="formRowId" name="rowId" size="1" value="" ><br />
									<label for="rowWeight">Weight</label> <input id="formRowWeight" name="rowWeight" size="1" value="" ><br />
  									<label for="rowLanguageId">Language</label> <select id="formRowLanguageId" name="rowLanguageId" ></select><br /> 
 	    							<label for="rowQuestionType">Type</label> <select id="formRowQuestionType" name="rowQuestionType" ></select><br />  
									<label for="rowQuestionText">Text</label> <textarea id="formRowQuestionText" name="rowQuestionText" cols="40" rows="3"> </textarea><br /><br />
								</sj:dialog>
							</tbody> 
						</table>
					</div>
					<button id="create-question">Add Question</button> &nbsp;
					<input type="submit" value="Cancel" class="ui-button ui-state-default ui-corner-all" onclick="location.href='<s:url namespace="/survey" action="list" includeParams="none" />'; return false;" /> &nbsp; 
					<button id="save-questions">Save All Questions</button>
				</div>
            </div> 
         </div>

